import "./UI.ts";

//游戏参数
let PIANO_TIME = 84.056;
const START_POSITION = new GameVector3(206.3, 12, 247.8);
const BLOCK_SCALE = new GameVector3(0.05, 0.05, 0.05);
// 相机位置偏移量常量
const CAMERA_POSITION_OFFSET = new GameVector3(-15, 20, -20);

// 胜利区域
let winZone = world.addZone({
    selector: "*",
    bounds: new GameBounds3(
        new GameVector3(596.1, 0, 602.8),
        new GameVector3(608.5, 9.4, 608.3)
    ),
});

winZone.onEnter(async ({ entity: blockWinner }) => {
    // 进入胜利区域时的逻辑
    if (
        !blockWinner ||
        (!blockWinner.id.endsWith("的线") && !blockWinner.hasTag?.("block"))
    ) return
    // 防止多次触发
    if (blockWinner._winHandled) return;
    blockWinner._winHandled = true;
    // 立即禁用碰撞和重力
    blockWinner.collides = false;
    blockWinner.gravity = false;
    world.querySelectorAll("player").forEach(async (player) => {
        if (player.block && player.block.id === blockWinner.id) {
            player.cameraTargeting = null
            player.control = false;
            player.cloning = true;
            player.collides = true;
            player.fixed = true;
            player.Jump = true;
            blockWinner.meshOrientation = new GameQuaternion(0.0, 0.383, 0.0, 0.926);
            player.player.colorLUT = "lut/Night1.lut";
            player.player.cameraEntity = null;
            // 终点动画
            // 显示胜利对话框，点击后传送
            await player.player.dialog({
                type: GameDialogType.SELECT,
                title: `胜利`,
                content: `完成关卡！\n100%`,
                options: ["返回大厅"],
            });
            try {
                await world.teleport("100459168", [player]);
            } catch (e: any) {
                world.say("传送失败：" + e.stack);
            }
        }
    });
});


//隐藏引导线
world.onPlayerJoin(async ({ entity }) => {
    const followLine = await entity.player.dialog({
        type: GameDialogType.SELECT,
        title: `欢迎`,
        content: `点击空格(跳跃键)开始游戏，如果开始了就可以转向\n是否开启引导线？`,
        options: ["开启", "关闭"],
    });
    if (!followLine) {
        world.querySelectorAll("*").forEach((entity) => {
            if (entity.id.startsWith("引导线")) {
                entity.meshInvisible = false;
            }
        });
        return;
    }
    if (followLine.value === "关闭") {
        world.querySelectorAll("*").forEach((entity) => {
            if (entity.id.startsWith("YD")) {
                entity.meshInvisible = true;
            }
        });
    } else if (followLine.value === "开启") {
        world.querySelectorAll("*").forEach((entity) => {
            if (entity.id.startsWith("YD")) {
                entity.meshInvisible = false;
            }
        });
    }
});
world.querySelectorAll("*").forEach((entity) => {
    if (entity.id.startsWith("YD")) {
        entity.meshInvisible = true;
    }
});



// 初始化所有非玩家实体
world.querySelectorAll("*").forEach(async (entity) => {
    if (!entity.player) {
        entity.fixedPosition = entity.position.clone();
        entity.fixedScale = entity.meshScale;
        entity.fixedCollides = entity.collides;
        entity.fixedFixed = entity.fixed;
        if (entity.id.startsWith("正方形赛道")) {
            entity.collides = true;
            entity.fixed = true;
        }
    }
});

// 玩家方块属性调节函数
function setPlayerBlockPhysics(
    /**玩家实体 */
    entity: any,
    /**是否碰撞 */
    collides: boolean,
    /**是否重力 */
    gravity: boolean
) {
    if (entity && entity.block) {
        entity.block.collides = collides;
        entity.block.gravity = gravity;
        entity.block.fixed = false;
    }
}

world.onPlayerJoin(async ({ entity }) => {
    entity.death = false;
    entity.player.colorLUT = "lut/Filmic6.lut";
    entity.control = true;
    entity.cloning = false;
    entity.clicking = 0;
    entity.block = world.createEntity({
        mesh: "mesh/方块-钢琴.vb",
        position: new GameVector3(0, 3, 0),
        meshScale: new GameVector3(0.05, 0.05, 0.05),
        collides: true,
        fixed: false,
        gravity: true,
    });
    entity.block.id = `${entity.player.name}的线`;
    entity.block.addTag("block");
    entity.block.showEntityName = true;
    entity.player.cameraMode = GameCameraMode.FIXED;
    entity.player.canFly = false;
    entity.player.enableAction0 = false;
    entity.player.enableAction1 = false;
    entity.player.enableCrouch = false;
    entity.player.enableDoubleJump = false;
    // 直接使用全局常量设置相机位置
    entity.player.cameraPosition = new GameVector3(
        entity.block.position.x + CAMERA_POSITION_OFFSET.x,
        entity.block.position.y + CAMERA_POSITION_OFFSET.y,
        entity.block.position.z + CAMERA_POSITION_OFFSET.z
    );
    entity.player.cameraTarget = entity.block.position.clone();
    entity.Jump = false;
    entity.player.invisible = true;
    entity.player.showName = false;
    entity.player.spectator = false;
    entity.going = "z";
    entity.player.cameraEntity = entity.block;
    entity.player.cameraFovY = 80.5;
    while (1) {
        entity.progress += 0.5;
        await sleep(500);
    }
});

world.onPress(async ({ button, entity }) => {
    if (button === GameButtonType.JUMP && entity.control) {
        if (entity.Jump == false) {
            entity.progress = 0;
            entity.cloning = true;
            entity.Jump = true;
            await sleep(2000);
            entity.player.music.sample = "audio/Piano.mp3";
        } else {
            if (entity.going === "x") {
                entity.going = "z";
            } else if (entity.going == "z") {
                entity.going = "x";
            }
        }
        // console.log(
        //     "第" +
        //     entity.clicking +
        //     "次点击，坐标:(" +
        //     Math.floor(entity.block.position.x * 100) / 100 +
        //     ", " +
        //     Math.floor(entity.block.position.y * 100) / 100 +
        //     ", " +
        //     Math.floor(entity.block.position.z * 100) / 100 +
        //     ")"
        // );
        entity.clicking += 1;
    }
});

world.onTick(() => {
    world.querySelectorAll("player").forEach(async (e) => {
        e.alwaysPercent = `${Math.ceil((e.progress / PIANO_TIME) * 100)}%`;
        // if (e.alwaysPercent == `60%`) {
        //     console.log('60%')
        // }
        if (e.Jump) {
            if (e.going === "x") {
                e.block.position.x += 1;
            } else if (e.going === "z") {
                e.block.position.z += 1;
            }

            if (e.block.position.y <= 3) {
                e.control = false;
                e.percent = `${Math.ceil((e.progress / PIANO_TIME) * 100)}%`;
                e.cloning = false;
            }
            if (e.block.position.y <= 3) {
                e.Jump = false;
                e.death = true;
                e.player.colorLUT = "lut/Night1.lut";
                await e.player.dialog({
                    type: GameDialogType.SELECT,
                    title: `失败`,
                    content: `失败！\n当前进度\n${e.percent}\n[当前Demo暂不支持复活]`,
                    options: ["重新开始"],
                });

                world.querySelectorAll("*").forEach(async (e) => {
                    if (!e.player) {
                        e.fixedPosition = e.position.clone();
                        e.fixedScale = e.meshScale;
                        e.fixedCollides = e.collides;
                        e.fixedFixed = e.fixed;
                        if (e.id.startsWith("跳舞的线-界外")) {
                            e.collides = true;
                            e.fixed = true;
                        }
                    }
                });
                e.going = "z";
                e.progress = 0;
                e.player.colorLUT = "lut/Filmic6.lut";
                e.player.music.sample = "";
                e.control = true;
                e.block.destroy();
                e.cloning = false;
                e.clicking = 0;

                e.block = world.createEntity({
                    mesh: "mesh/方块-钢琴.vb",
                    position: new GameVector3(0, 3, 0),
                    meshScale: new GameVector3(0.05, 0.05, 0.05),
                    collides: true,
                    fixed: false,
                    gravity: true,
                });

                // 直接使用全局常量设置相机位置
                e.player.cameraPosition = new GameVector3(
                    e.block.position.x + CAMERA_POSITION_OFFSET.x,
                    e.block.position.y + CAMERA_POSITION_OFFSET.y,
                    e.block.position.z + CAMERA_POSITION_OFFSET.z
                );
                e.player.cameraTarget = e.block.position.clone();
                e.block.id = e.player.name;
                e.block.addTag("block");
                e.block.showEntityName = true;
                e.death = false;
                world.querySelectorAll(`.${e.player.userId}`).forEach(async (e1) => {
                    for (let i = 0; i <= 100; i++) {
                        await sleep(10);
                    }
                    e1.destroy();
                });
            }
            if (e.cloning) {
                // 直接使用全局常量设置相机位置
                e.player.cameraPosition = new GameVector3(
                    e.block.position.x + CAMERA_POSITION_OFFSET.x,
                    e.block.position.y + CAMERA_POSITION_OFFSET.y,
                    e.block.position.z + CAMERA_POSITION_OFFSET.z
                );


                e.player.cameraTarget = e.block.position.clone();
                let block_body = world.createEntity({
                    id: "block_body",
                    position: e.block.position.clone(),
                    meshScale: new GameVector3(0.00000001, 0.00000001, 0.00000001),
                    collides: false,
                    fixed: true,
                    gravity: false,
                });
                if (!block_body) return;
                block_body.addTag(e.player.userId);
                block_body.mesh = "mesh/方块-钢琴.vb";
                await sleep(125);
                block_body.meshScale = new GameVector3(0.05, 0.05, 0.05);
                await sleep(10000);
                if (e.death === false) {
                    block_body.destroy();
                }
            }
        }
    });
});
